package com.qs.user.ui.VM;

import android.app.Application;
import android.databinding.BindingAdapter;
import android.databinding.ObservableBoolean;
import android.databinding.ObservableField;
import android.support.annotation.NonNull;
import android.widget.ImageView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.qs.base.data.BaseData;
import com.qs.base.global.SPKeyGlobal;
import com.qs.base.router.RouterActivityPath;
import com.qs.base.utils.RetrofitClient;
import com.qs.user.R;
import com.qs.user.api.ApiService;
import com.qs.user.entity.LoginEntity;
import com.qs.user.pay.util.GeneralUtils;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 我的主页面vm
 *
 * @Author ltzz
 * @Date 2019/8/8
 */
public class UserMainViewModel extends BaseViewModel {
    public UserMainViewModel(@NonNull Application application) {
        super(application);
    }

    //用户帐号
    public String userId = "";
    //用户名
    public ObservableField<String> userName = new ObservableField<>("点击登录");
    //用户头像
    public ObservableField<String> userImg = new ObservableField<>("");
    //识别次数
    public ObservableField<String> seeNumber = new ObservableField<>("0");
    //翻译次数
    public ObservableField<String> translateNumber = new ObservableField<>("10000");

    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();

    public class UIChangeObservable {
        //登录点击
        public ObservableBoolean login = new ObservableBoolean(false);
        //退出登录
        public ObservableBoolean logOut = new ObservableBoolean(false);
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onResume() {
        super.onResume();
        //查询用户信息
        userId = SPUtils.getInstance().getString(SPKeyGlobal.USER_ID, "");
        userName.set(SPUtils.getInstance().getString(SPKeyGlobal.USER_NAME, "点击登录"));
        userImg.set(SPUtils.getInstance().getString(SPKeyGlobal.USER_IMG, ""));

        boolean isOk = false;
        if (!StringUtils.isTrimEmpty(SPUtils.getInstance().getString(SPKeyGlobal.USER_ID))) {
            //用户已登录
            //查看是否是会员
            String date = SPUtils.getInstance().getString(SPKeyGlobal.USER_DATE, "");
            if(!date.contains("无限")){
                if (!StringUtils.isTrimEmpty(date)) {
                    if (Float.parseFloat(date) > 0) {
                        isOk = true;
                        seeNumber.set("无限");
                    }
                }
            }else{
                isOk = true;
                seeNumber.set("无限");
            }
        }
        if (!isOk) {
            //不是会员
            seeNumber.set(SPUtils.getInstance().getString(SPKeyGlobal.SEE_NUMBER, ""));
        }
        //查询次数
        if (!StringUtils.isTrimEmpty(userId)) {
            //已登录就去服务器查询
            getNumbersByUserid(userId);
        } else {
            //未登录获取本地存储数据
            seeNumber.set(SPUtils.getInstance().getString(SPKeyGlobal.SEE_NUMBER, ""));
            translateNumber.set(SPUtils.getInstance().getString(SPKeyGlobal.TRANSLATE_NUMBER, ""));
        }
    }

    //登录点击事件
    public BindingCommand userClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (StringUtils.isTrimEmpty(userId))
                uc.login.set(!uc.login.get());
        }
    });
    //会员中心
    public BindingCommand memberCenterClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            ARouter.getInstance().build(RouterActivityPath.User.MEMBER_CENTER_ACTIVITY).navigation();
        }
    });
    //识别历史
    public BindingCommand oldClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            ARouter.getInstance().build(RouterActivityPath.User.IDENTIFY_HISTORICAL_ACTIVITY).navigation();
        }
    });
    //我的文件
    public BindingCommand myFileClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            ARouter.getInstance().build(RouterActivityPath.User.MY_FILE_ACTIVITY).navigation();
        }
    });
    //联系客服
    public BindingCommand relationClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            ToastUtils.showShort("联系客服");
        }
    });
    //关于我们
    public BindingCommand aboutUsClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            ARouter.getInstance().build(RouterActivityPath.User.ABOUT_USR_ACTIVITY).navigation();
        }
    });
    //退出登录
    public BindingCommand logOutClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.logOut.set(!uc.logOut.get());
        }
    });

    /**
     * 登录
     *
     * @param imagePath
     * @param pwd
     * @param login
     * @param userName1
     */
    public void register(final String imagePath, final String login, String pwd, final String userName1) {

        String json = GeneralUtils.getJson(new String[]{"User_Name", "User_Phone", "User_Pwd"}, new String[]{StringUtils.isTrimEmpty(userName1) ? "" : userName1, login, pwd});
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        RetrofitClient
                .getInstance()
                .create(ApiService.class)
                .register(BaseData.APPNAME, body)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) //请求与View周期同步
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) {
                        showDialog();
                    }
                })
                .subscribe(new Consumer<LoginEntity>() {
                    @Override
                    public void accept(LoginEntity loginEntity) throws Exception {
                        dismissDialog();
                        if ("SUCCESS".equals(loginEntity.getCreateState()) || "Account Exist".equals(loginEntity.getCreateState())) {
                            SPUtils.getInstance().put(SPKeyGlobal.USER_ID, login);
                            SPUtils.getInstance().put(SPKeyGlobal.USER_NAME, userName1);
                            SPUtils.getInstance().put(SPKeyGlobal.USER_IMG, imagePath);
                            ToastUtils.showShort("登录成功");
                            userId = login;
                            userName.set(userName1);
                            userImg.set(imagePath);
                            //请求翻译次数
                            getNumbersByUserid(login);
                            //请求会员信息
                            getVIPInfo(login);
                        } else {
                            ToastUtils.showShort("登录失败，请重试");
                        }

                        if ("SUCCESS".equals(loginEntity.getCreateState())) {
                            //注册成功，添加剩余数量
                            addNumbers(userId, 10000 + "");
                        }
                    }

                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //异常
                        //模拟成功
                        dismissDialog();
                        ToastUtils.showLong("请求超时...");
                    }
                });
    }




    /**
     * 剩余翻译次数
     *
     * @param userid
     */
    public void getNumbersByUserid(String userid) {

        Map<String, Object> map = new HashMap<>();
        map.put("userid", userid);
        RetrofitClient
                .getInstance()
                .create(ApiService.class)
                .getNumbersByUserid(map)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) //请求与View周期同步
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) {
                    }
                })
                .subscribe(new Consumer<Map<String, Object>>() {
                    @Override
                    public void accept(Map<String, Object> baseResult) throws Exception {
                        if (baseResult != null) {
                            String number = baseResult.get("numbers").toString();
                            if (StringUtils.isTrimEmpty(number))
                                translateNumber.set("0");
                            else
                                translateNumber.set(number);
                        }
                    }

                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //异常
                        ToastUtils.showLong("翻译剩余字数获取失败..");
                    }
                });
    }

    //会员剩余天数
    public void getVIPInfo(String userid) {

        Map<String, Object> map = new HashMap<>();
        map.put("appname", BaseData.APPNAME);
        map.put("userphone", userid);
        RetrofitClient
                .getInstance()
                .create(ApiService.class)
                .getVIPInfo(map)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) //请求与View周期同步
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) {
                    }
                })
                .subscribe(new Consumer<Map<String, Object>>() {
                    @Override
                    public void accept(Map<String, Object> baseResult) throws Exception {
                        if (baseResult != null) {
                            String day = baseResult.get("day").toString();
                            if (StringUtils.isTrimEmpty(day)) {
                                SPUtils.getInstance().put(SPKeyGlobal.USER_DATE, 0);
                            } else {
                                SPUtils.getInstance().put(SPKeyGlobal.USER_DATE, day);
                                if (!StringUtils.equals(day, "0")) {
                                    seeNumber.set("无限");
                                }
                            }
                        }
                    }

                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //异常
                    }
                });
    }


    /**
     * 添加翻译次数
     *
     * @param userid
     * @param wordnumber
     */
    public void addNumbers(final String userid, String wordnumber) {

        Map<String, Object> map = new HashMap<>();
        map.put("userid", userid);
        map.put("wordnumber", wordnumber);
        Gson gson = new Gson();
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), gson.toJson(map));

        RetrofitClient
                .getInstance()
                .create(ApiService.class)
                .addNumbers(body)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) //请求与View周期同步
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) {
                    }
                })
                .subscribe(new Consumer<Map<String, Object>>() {
                    @Override
                    public void accept(Map<String, Object> baseResult) throws Exception {
                        dismissDialog();
                        if (baseResult != null && Integer.parseInt(baseResult.get("code").toString()) == 0) {
                            //请求翻译次数
                            getNumbersByUserid(userid);
                        }
                    }

                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //异常
                        //模拟成功
                        dismissDialog();
                    }
                });
    }


    @BindingAdapter({"imageUrl"})
    public static void loadImage(ImageView imageView, String url) {
        RequestOptions mRequestOptions = new RequestOptions()
                .override(imageView.getWidth(), imageView.getHeight())
//                .bitmapTransform(new RoundedCorners(5))
                .circleCropTransform()
                .error(R.drawable.user_member_user);
        Glide.with(imageView.getContext())
                .load(url)
                .apply(mRequestOptions)
                .into(imageView);
    }
}
